package com.nsgf.library.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;

import androidx.core.content.FileProvider;
import androidx.appcompat.app.AlertDialog;

import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.text.DecimalFormat;
import com.nsgf.library.R;

/**
 * ****************************
 * 项目名称：demo_sc
 * Authro:gc
 * 创建时间：2020/1/21 13:50
 * 用户：
 * ****************************
 **/
public class UpdateService {
    private DownloadManager mDownloadManager;
    private Activity mContext;
    private long downloadId;
    private String apkName = Kits.Date.getTimeStame().concat("_skjz.apk");

    public UpdateService() {

    }

    public UpdateService(Activity context) {
        mContext = context;
    }

    public void download(String url, String name) {
        final String packageName = "com.android.providers.downloads";
        int state = mContext.getPackageManager().getApplicationEnabledSetting(packageName);
        //检测下载管理器是否被禁用
        if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setTitle("温馨提示").setMessage
                    ("系统下载管理器被禁止，需手动打开").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    try {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + packageName));
                        mContext.startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
                        mContext.startActivity(intent);
                    }
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        } else {
            //正常下载流程
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setAllowedOverRoaming(false);

            //通知栏显示
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("水库矩阵");
            request.setDescription("正在下载中...");
            request.setVisibleInDownloadsUi(true);
            //设置下载的路径
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, apkName);
            //获取DownloadManager
            mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            downloadId = mDownloadManager.enqueue(request);
            startQuery();

            mContext.registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };

    /**
     * 检查下载状态
     */
    @SuppressLint("Range")
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        Cursor cursor = mDownloadManager.query(query);
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //下载暂停
                case DownloadManager.STATUS_PAUSED:
                    break;
                //下载延迟
                case DownloadManager.STATUS_PENDING:
                    break;
                //正在下载
                case DownloadManager.STATUS_RUNNING:
                    int mDownload_all = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                    int mDownload_so_far = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                    Message msg = Message.obtain();
                    if (mDownload_all > 0) {
                        msg.what = 1001;
                        msg.arg1 = mDownload_so_far;
                        msg.arg2 = mDownload_all;
                        mHandler.sendMessage(msg);
                    }
                    break;
                //下载完成
                case DownloadManager.STATUS_SUCCESSFUL:
                    stopQuery();
                    installAPK();
                    mContext.finish();
                    break;
                //下载失败
                case DownloadManager.STATUS_FAILED:
                    Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
        cursor.close();
    }


    /**
     * 7.0兼容
     */
    private void installAPK() {
        File apkFile =
                new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);
    }

    private final QueryRunnable mQueryProgressRunnable = new QueryRunnable();
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1001) {
                if (progressBar != null) {
                    progressBar.setProgress(msg.arg1);
                    DecimalFormat df = new DecimalFormat("#####0.00");
                    try {
                        tv_progress.setText(df.format(Double.parseDouble(String.valueOf(msg.arg1)) / (Double.parseDouble(String.valueOf(msg.arg2))) * 100) + "%");
                    } catch (Exception e) {
                        e.getMessage();
                    }
                    progressBar.setMax(msg.arg2);
                }
            }
        }
    };

    //更新下载进度
    private void startQuery() {
        if (downloadId != 0) {
            showUpdataVersion();
            mHandler.post(mQueryProgressRunnable);
        }
    }

    //查询下载进度
    private class QueryRunnable implements Runnable {
        @Override
        public void run() {
            checkStatus();
            showUpdataVersion();
            mHandler.postDelayed(mQueryProgressRunnable, 100);
        }
    }

    //停止查询下载进度
    private void stopQuery() {
        mHandler.removeCallbacks(mQueryProgressRunnable);
    }

    //下载停止同时删除下载文件
    private void removeDownload() {
        if (mDownloadManager != null) {
            mDownloadManager.remove(downloadId);
        }
    }

    private Dialog dialogDownload;
    ProgressBar progressBar;
    TextView tv_progress;

    private void showUpdataVersion() {
        if (dialogDownload == null) {
            dialogDownload = new Dialog(mContext, R.style.dialog_style);
            View view = View.inflate(mContext, R.layout.dialog_updata_version_download, null);
            progressBar = view.findViewById(R.id.progressBar);
            tv_progress = view.findViewById(R.id.tv_progress);
            dialogDownload.setContentView(view);
        }
        dialogDownload.setCancelable(false);
        dialogDownload.show();

    }
}